package com.xx.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.xx.springboot.entity.CommonResult;
import com.xx.springboot.entity.Contains;
import com.xx.springboot.entity.ResponseBo;
import com.xx.springboot.entity.User;
import com.xx.springboot.service.IUserService;
import com.xx.springboot.service.impl.QQAuthServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @author: xiaoxi
 * @description: 用户登录接口, 使用 SHIRO
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private IUserService userService;

    @Autowired
    private QQAuthServiceImpl qqAuthService;

    /**
     * <p>
     *     用户登录
     * </p>
     * @return
     */
    public CommonResult loginUser(String username, String password){
       return userService.loginUser(username, password);
    }

    @PostMapping("/shiroLogin")
    public ResponseBo shiroLogin(String userName, String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password, true);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return ResponseBo.ok(subject.getPrincipal());
        }
        catch (Exception ex){
            return ResponseBo.error(ex.getMessage());

        }
    }

    @RequestMapping("/qqLogin")
    public void shiroLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        logger.info("第三方, 关联登录, 用户名:{}, 密码: {}", userName, password);
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password, true);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            response.sendRedirect(Contains.BLOG_PAGE_PATH);
        }
        catch (Exception ex){
            System.out.println(ex.getMessage());
            response.sendRedirect(Contains.BLOG_PAGE_PATH_OLD);
        }
    }


    /**
     * 判断是否登录
     * @return
     */
    @RequestMapping("/isLogin")
    public ResponseBo isLogin(HttpServletRequest request){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        return user != null ? ResponseBo.ok(user) : ResponseBo.error();
    }

    /**
     * 注销登录
     * @return
     */
    @RequestMapping("/logout")
    public ResponseBo logout(){
        SecurityUtils.getSubject().logout();
        return ResponseBo.ok();
    }

    @RequestMapping("/addUser")
    public void addUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String accessToken = request.getParameter("accessToken");
        String openId = request.getParameter("openId");
        JSONObject userInfo = qqAuthService.getUserInfo(accessToken, openId);
        User user = new User();
        user.setOpenId(userInfo.getString("id"));
        user.setUsername(userInfo.getString("userName"));
        user.setLoginName(userInfo.getString("id"));
        user.setHeaderPic(userInfo.getString("headImg"));
        user.setCreateTime(new Date(System.currentTimeMillis()));
        user.setPassword(userInfo.getString("id"));
        user.setStatus(1);
        boolean flag = userService.save(user);
        if (flag) {
            response.sendRedirect(Contains.SERVER_ADDRESS + "/login/qqLogin?userName=" + user.getLoginName() + "&password=" + user.getOpenId());

        }

    }

}
